<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools title="数据信息20条">
        <el-button v-if="$store.state.user.userInfo.roles.points.includes('import_excel')" type="warning" size="small" @click="abc">导入excel</el-button>
        <el-button v-if="$store.state.user.userInfo.roles.points.includes('export_excel')" type="danger" size="small" @click="excel">导出excel</el-button>
        <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table :data="list" border :default-sort="{ prop: 'workNumber' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id='+scope.row.id
                )"
              >查看</el-button>
              <el-button type="text" size="small" @click.native="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2, 5, 10]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
        <el-dialog title="新增员工" :visible.sync="showDialog">
          <emp-dialog v-if="showDialog" @success="success" />
        </el-dialog>
      </el-card>
    </div>
    <el-dialog :visible.sync="showDialogRole" title="分配角色">
      <assign-role v-if="showDialogRole" :cur-id="curId" @close="close" />
    </el-dialog>
  </div>
</template>
<script>
const type = { '1': '正式', '2': '非正式' }
// 导入组件
import AssignRole from './assignRole'
import empDialog from './empDialog.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
export default {
  components: { empDialog, AssignRole },
  data() {
    return {
      list: [],
      page: 1, // 当前页码
      size: 5, // 每页几条
      total: 0, // 总共数据条数
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 获取员工信息,并保存
    async loadEmployeeList() {
      const res = await getEmployeeList({ page: this.page, size: this.size })
      console.log('员工列表', res.data)
      this.list = res.data.rows
      this.total = res.data.total
    },
    format(type) {
      if (type == '1') {
        return '正式'
      } else if (type == '2') {
        return '非正式'
      }
    },
    hCurrentChange(curPage) {
      this.page = curPage
      this.loadEmployeeList()
    },
    hSizeChange(curSize) {
      this.size = curSize
      this.loadEmployeeList()
    },
    // 实现删除具体操作
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
        this.$message.success(res.message)
      } catch (err) {
        console.log(err)
      }
    },
    // 用户点击删除
    hDel(id) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    // 用户点击新增按钮
    hAdd() {
      this.showDialog = true
    },
    // 关闭弹框
    success() {
      this.showDialog = false
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    },
    abc() {
      this.$router.push('/import')
    },
    formatData(rows) {
      const mapobj = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const enheader = Object.keys(rows[0])
      const header = enheader.map(en => mapobj[en])
      const data = rows.map(obj => {
        obj.formOfEmployment = type[obj.formOfEmployment]
        return Object.values(obj)
      }
      )
      return { header, data }
    },
    async  excel() {
      const res = await getEmployeeList({ page: this.page, size: this.size })
      // 对数据格式进行转换
      const { header, data } = this.formatData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        // 准备数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)

        // 生成excel
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    close() {
      this.showDialogRole = false
    }
  }
}
</script>
